package com.l.demo.exception;

import com.l.demo.model.ReqResult;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * controller统一异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public ReqResult handleBindException(BindException e)
    {
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return ReqResult.fail(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ReqResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
    {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return ReqResult.fail(message);
    }


    /**
     * 系统异常
     */
    @ExceptionHandler({Exception.class, RuntimeException.class})
    public ReqResult handleException(Exception e)
    {
        return ReqResult.fail(e.getMessage());
    }
}
